import { login, logout, getInfo, Mylogin } from '@/api/user'
import { getToken, setToken, removeToken, getCookie, removeCookie, setCookie } from '@/utils/auth'
import router, { resetRouter } from '@/router'
const state = {
  token: getToken(),
  nickName: '',
  username: '',
  // password: '',
  avatar: '',
  roles: [],
  storeId: '',
  id: '',
  hasRoles: [],
  firstLogin: false,
}

const mutations = {
  SET_FLOGIN: (state, boolean) => {
    state.firstLogin = boolean
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_COOKIE: (state, cookie) => {
    state.cookie = cookie
  },

  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickName = nickname
  },
  // SET_PASSWORD: (state, password) => {
  //   state.password = password
  // },
  SET_STOREID: (state, storeId) => {
    state.storeId = storeId
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  //解决第一次进入没有菜单问题
  SET_HROLES: (state, hasRoles) => {
    state.hasRoles = hasRoles
  }
}

const actions = {
  // user login
  // login({ commit }, userInfo) {
  //   const { id, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ id: id.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  // user mylogin
  Mylogin({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      Mylogin({ username: username.trim(), password: password }).then(response => {
        // console.log(response)
        if (response.returnValue == 1) {
          const { data, map } = response
          const avatar = 'https://img.zcool.cn/community/01a0465ff716ba11013ee04d4faf3c.gif'
          const { token } = map;
          const { roles, username, storeId, id, nickname } = data
          let rolesArr = []
          for (var item of roles) {
            rolesArr.push(item.name)
          }
          commit("SET_ROLES", rolesArr);
          commit('SET_USERNAME', username)
          // commit('SET_PASSWORD', data.password)
          commit('SET_STOREID', storeId)
          commit('SET_ID', id)
          commit('SET_TOKEN', token)
          commit('SET_NICKNAME', nickname)
          commit('SET_AVATAR', avatar)
          commit('SET_FLOGIN', false)
          setToken(token)
          resolve(response);
        }
        else {
          resolve(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     const data = {
  //       roles: ['editor'],
  //       introduction: 'I am an editor',
  //       avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
  //       name: 'Normal Editor'
  //     }
  //     const { roles, name, avatar, introduction } = data
  //     // roles must be a non-empty array
  //     if (!roles || roles.length <= 0) {
  //       reject('getInfo: roles must be a non-null array!')
  //     }
  //     commit('SET_ROLES', roles)
  //     commit('SET_NAME', name)
  //     commit('SET_AVATAR', avatar)
  //     commit('SET_INTRODUCTION', introduction)
  //     resolve(data)
  //   })
  // },

  //传递roles
  hasRoles({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.roles.length > 0) {
        commit('SET_HROLES', state.roles)
        resolve(state.roles);
      }
      else {
        reject();
      }
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // console.log(state.token);
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_USERNAME', '')
        commit('SET_STOREID', '')
        commit('SET_ID', '')
        commit('SET_HROLES', [])
        commit('SET_FLOGIN', true)
        commit('SET_NICKNAME', '')
        removeToken()
        // commit('SET_COOKIE','')
        // commit('SET_ROLES',[])
        // removeCookie();
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USERNAME', '')
      commit('SET_STOREID', '')
      commit('SET_ID', '')
      commit('SET_HROLES', [])
      commit('SET_FLOGIN', true)
      commit('SET_NICKNAME', '')
      removeToken()
      resetRouter()
      resolve()
    })
  },


  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
